package com.vmss.cspider.dao;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import java.sql.Connection;
import java.util.Map;

public class DBUtil {
	
	/**
	 * 获取mysql连接
	 * @return
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	public static Connection getConnection() throws SQLException, ClassNotFoundException
	{
		String url = "jdbc:mysql://localhost:3306/vmssdb";
		Class.forName("com.mysql.jdbc.Driver");
		String username = "root";
		String password = "vmss";
		Connection conn = DriverManager.getConnection(url, username, password);
		return conn;
	}
	
	public static boolean insertToDB( Map < String, Object>pMap ) throws SQLException, ClassNotFoundException
	{
		StringBuffer fieldBuff = new StringBuffer();
		StringBuffer valueBuff = new StringBuffer();
		for (Map.Entry<String, Object> entry : pMap.entrySet()) {  
            String key = entry.getKey();  
            Object value = entry.getValue();  
            fieldBuff.append(key);  
            fieldBuff.append(","); 
            if( value instanceof String )
            {
            	value = "'"+value+"'";
            }
            valueBuff.append(value);  
            valueBuff.append(",");  
        }
		
		
		String fieldStr = fieldBuff.substring(0, fieldBuff.length()-1 );	//截取最后一个逗号
		String valueStr = valueBuff.substring(0, valueBuff.length()-1 );	//截取最后一个逗号
		String sql = "insert into s_spider_data ("+ fieldStr + ") values ( " +valueStr +") ";
		System.out.println(sql);
		
		Connection conn = DBUtil.getConnection();
		Statement stmt = conn.createStatement();
		boolean isSucc = stmt.execute(sql);
		stmt.close();
		conn.close();
		
		return isSucc;
	}
}
